#include "tcheckboxdelegate.h"

TCheckBoxDelegate::TCheckBoxDelegate()
{

}

void TCheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionButton *btnStyle = new QStyleOptionButton;
    btnStyle->rect = option.rect;            //设置按钮区域为当前item的rect
    bool state = index.data().toBool();
    //qDebug()<<"row="<<index.row()<<"state="<<state;
    if(state)
    {
        btnStyle->state = QStyle::State_Enabled|QStyle::State_On; //设置按钮状态
    }
    else
    {
        btnStyle->state = QStyle::State_Enabled|QStyle::State_Off; //设置按钮状态
    }

    QCheckBox *chkBox = new QCheckBox;
    chkBox->style()->drawControl(QStyle::CE_CheckBox, btnStyle, painter,chkBox);   //将按钮绘制出来
}

bool TCheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
    if(option.rect.contains(mouseEvent->pos()))
    {
        //此次将会发送两次信号（按下触发和释放触发），若只需要一次信号则添加判断即可
        //判断按下：event->type() == QEvent::MouseButtonPress
        //判断释放：event->type() == QEvent::MouseButtonRelease
        if(event->type() == QEvent::MouseButtonPress)
        {
            //qDebug()<<"set row="<<index.row();
            // model->setData(index,QVariant(!index.data().toBool()),Qt::DisplayRole);
            // model->dataChanged(index,index);
            emit clicked(model,index);
        }
    }
    return true;
}
